import axios from 'axios'
import qs from 'qs'
import Vue from '../main.js'

const ERR_OK = 0
const ERR_LOGIN = 99

const Axios = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? '/api' : '/',
    timeout: 20000,
    responseType: 'json',
    withCredentials: true, // 是否允许带cookie这些
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
        //'Access-Control-Allow-Origin': '*',
        //'Access-Control-Allow-Methods': 'PUT,GET,POST,OPTIONS',
        //'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type, X-File-Name',
    }
})

let CancelToken = axios.CancelToken

// POST传参序列化(添加请求拦截器)
Axios.interceptors.request.use(
    config => {
        /*config.cancelToken = new CancelToken(function executor (c) {
            // executor 函数接收一个 cancel 函数作为参数
            Vue.$store.state.app.cancelApi = c
        });*/
        // 在发送请求之前做某件事
        if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
            // 序列化
            if (config.headers['Content-Type'] !== 'multipart/form-data') {
                config.data = qs.stringify(config.data)
            }
        }
        return config
    },
    error => {
        return Promise.reject(error.data.error.message)
    }
)

// 返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
    res => {
        if (res.data) {
            if (res.data && res.data.status == ERR_LOGIN) {
//            location.href = res.data.data.url
            }
            return new Promise((resolve) => {
                resolve(res.data)
            })
        } else {
            return Promise.reject('请求异常')
        }
    },
    error => {
        if (error.message) {
            return Promise.reject(error.message)
        }
        /*if (error.response.status === 403) {
            Vue.$router.push({
                name: 'error-403'
            })
        }
        if (error.response.status === 500) {
            Vue.$router.push({
                name: 'error-500'
            })
        }
        if (error.response.status === 502) {
            Vue.$router.push({
                name: 'error-502'
            })
        }
        if (error.response.status === 404) {
            Vue.$router.push({
                name: 'error-404'
            })
        }*/
        // 返回 response 里的错误信息
        const errorInfo = error.data.error ? error.data.error.message : error.data
        return Promise.reject(errorInfo)
    }
)

export default Axios